/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Chen weihan <csq-3@163.com>
 * @since : 2014年08月12日 星期二 14时59分39秒
 * @filename : seams/static/mnm/src/joinus.js
 * @version : 
 * @description : 
 */
define(function(require, exports, module) {

      require("{remoteUrl}css/mnm/public.css");
      require("{remoteUrl}css/mnm/share.css");
      require("{remoteUrl}css/mnm/joinus.css");
      require("{baseSea}mobiscroll/css/mobiscroll.dev.css");
      var tempObj = {},
          $ = require('zepto'),
	  ejs = require('ejs'),
          util = require('{baseSea}util/util'),
          upload = require('{baseSea}upload/upload'),
	  tab = require('{baseSea}tab/zepto.tab.js'),
	  mobiscroll = require('{baseSea}mobiscroll/mobiscroll.dev'),
          lang = require('{baseSea}I18N/{locale}'),
          share = require('./share'),
          tpl = require('{tplUrl}joinus.tpl'),
          ctpl = require('{tplUrl}countryList.tpl');
 
      function Joinus() {};

      module.exports = Joinus;

      Joinus.prototype.render = function(tabNum) {
           if ($('#joinus_box').length < 1) { 
              this._init();
           } else {
              $('#joinus_box').show();
           }

           if (parseInt(tabNum)==1) {
              tab.gotoTabs(1);
           } else {
              tab.gotoTabs(0);
           }

      };

      Joinus.prototype.gotoTabs = function(num) {
            tab.gotoTabs(num);
      };

      Joinus.prototype._init = function() {
          this._ejs();
          this._bindEvt();
          tab.init({});
          this._upload(); 
          this._countryList();

      };

      Joinus.prototype._upload = function() {
          upload.init({
	       id : 'file',
	       filter: 'image',
	       maxsize: 2048000,
	       //url: ENV.domain+'server/upload.php',
	       url:seajs.data.vars.apiUrl+'basic_tmp_picture',
	       onSuccess: function(data){var data = JSON.parse(data);tempObj.img = data.url},
	       onError: function(data){console.log(data)},
	       onProgress: function(evt){
		       var width = Math.round(evt.loaded /evt.total * 100);   
		       if (width == 100) {
			    width = 0; 
		       }
		       $('#progress').css('width',width+'px');  
		    },
	       onReader: function(evt){$('#img_show').html('<img src="'+evt.target.result+'" alt=""/>');} 
          });
      };

      Joinus.prototype._countryList = function() {
          var tthis=this,obj = {
		 url : seajs.data.vars.apiUrl+'basic_country_list',
		 type : 'GET',
		 success : function(data) {
		     if (data.error == 0 ) {
			 var html = ejs.render(ctpl, {arr:data.data});
			     $('.loction').html(html);
			     tthis._ajaxConutryBind(); 
		     }
		 },
		 error : function(xhr, errorType, error) {
			 alert('basic_country_list api is failed!');
		 } 
             };
          $.ajax(util.ajaxControl(obj)); 
      };

      Joinus.prototype._ajaxConutryBind = function() {
	  $('#country').scroller('destroy').scroller($.extend({preset: 'select'},{
		theme: 'android-holo light',
		mode: 'scroller',
		lang: '',
		display: 'bottom',
		animate: '',
		placeholder :'Country',
		inputClass:'input_location',
		name:'loction'
	  }));
      };

      Joinus.prototype._bindEvt = function() {
          var tthis = this; 
          $("#joinus_box").find('.joinus_back').on('tap',function(){
	       if (tab.info.index > 0) {
		   window.location.href='#name=joinus&type=div'; 
	       } else {
		   window.location.href='#name=index'; 
	       }
          }); 

          $(".jbc-frist").on('tap',function(){
               tthis._handleFristData();
          });
    
          $(".jbc-second").on('tap',function(){
               tthis._handleSecondData();
          });
 
	  var opt = {
	        'date': {
		    preset: 'date',
		    dateFormat: 'yy-mm-dd',
	        }
	      };

	  $('#age').scroller('destroy').scroller($.extend(opt['date'], {
		theme: 'android-holo light',
		mode: 'scroller',
		lang: '',
		display: 'bottom',
		animate: ''
	  })); 

          $(".gender_item").on('tap',function(){
             $(this).parent().find(".gender_item").each(function(){
                 var type = $(this).attr('type');
                 $(this).removeAttr('select').removeClass('gender_item_'+type+'_select').find('div').removeClass(type+'_select').addClass(type);      
             });
             var type = $(this).attr('type');
             $(this).attr('select',true).addClass('gender_item_'+type+'_select').find('div').removeClass(type).addClass(type+'_select');
          });  
 
      };

      Joinus.prototype._handleFristData = function() {
	    var bool=false,obj={};
		obj.email = $("#joinus_box").find('input[name="email"]').val(),
		obj.userName = $("#joinus_box").find('input[name="userName"]').val(),
		obj.passWord = $("#joinus_box").find('input[name="passWord"]').val();
	    //格式验证        
	    bool = this._regModelValidata(obj);
	    //bool = true; 
	    //ajax是否存在验证 
            //window.location.href='#name=joinus&type=div&tab=1'; 
	    if (bool) {
		if ($('.jbc-frist').attr('ajax') != 1) {
		    this._ajaxFristData(obj);
		    util.cloneObj(obj,tempObj); 
		}
	    } else {
		console.log('前端验证没通过！'); 
	    }
      };

      Joinus.prototype._optionVal = function(id,val) {
            return $('#'+id).find('option[val="'+$.trim(val)+'"]').val();
      };

      Joinus.prototype._handleSecondData = function() {
	    var bool = false, obj = {};
	    obj.gender = $('#joinus_second').find('.gender_item[select=true]').attr('type');
	    obj.age = $("#joinus_box").find('input[name="age"]').val();
	    obj.loction = this._optionVal('country',$("#country_dummy").val());
	    obj.zipCode = $("#joinus_box").find('input[name="zipCode"]').val();

	    //格式验证        
	    bool = this._regModelValidata(obj); 
	    //bool = true; 
	    if (bool) {
		util.cloneObj(obj,tempObj); 
		this._ajaxRegData();                
	    } else {
		console.log('前端验证没通过！'); 
	    }
      };

      Joinus.prototype._ejs = function() {
            var html = ejs.render(tpl,lang); 
                $('body').append(html);  
      };

      Joinus.prototype._ajaxFristData = function(data) {

	    $('.jbc-frist').attr('ajax',1);
	    share.ajaxStartA($('.jbc-frist'));

	    var tthis = this,regAccountModel = {
		   username: data.userName,
		   email: data.email,
		   password: data.passWord
		};
    
	    var obj = {
		     url : seajs.data.vars.apiUrl+'user_account',
		     type : 'POST',
		     data : regAccountModel,
		     success : function(data) {
				 $('.jbc-frist').attr('ajax',0);
				 share.ajaxEndA($('.jbc-frist'));
                                     
				 if (data.error == 0 ) {
		                     window.location.href='#name=joinus&type=div&tab=1'; 
                                 } else {
				     var obj = {};
				     switch(data.data[0].error_id) {
					case 1:
					    obj = {bool : false, field:'userName', msg:data.data[0].msg};
					break;
					case 2:
					    obj = {bool : false, field:'email', msg:data.data[0].msg};
					break;
					case 3:
					    obj = {bool : false, field:'passWord', msg:data.data[0].msg};
					break;
				     };
				     tthis._renderError(obj);
				 }
		       },
		       error : function(xhr, errorType, error) {
				 alert('http request failed!');
		       } 
	     };
	  $.ajax(util.ajaxControl(obj)); 
      };

      Joinus.prototype._ajaxRegData = function() {
	    $('.jbc-second').attr('ajax',1);
	    share.ajaxStartA($('.jbc-second'));
	       
	    var regModel = {
		username: tempObj.userName,
		email: tempObj.email,
		password: tempObj.passWord,
		img: tempObj.img,
		gender: this._gender(tempObj.gender),
		age: share.ages(tempObj.age),
		r_country: tempObj.loction,
		r_zip: tempObj.zipCode,
	    };
	    
	    console.log(regModel);
     
	    var obj = {
		url : seajs.data.vars.apiUrl+'user_register',
		type : 'POST',
		data : regModel,
		success : function(data) {
			 $('.jbc-second').attr('ajax',0);
			 share.ajaxEndA($('.jbc-second'));
			 if (data.error == 0 ) {
			     alert('reg success!');
			 } else {
			     alert('error');
			 } 
		},
	        error : function(xhr, errorType, error) {

		} 
	     };
	     $.ajax(util.ajaxControl(obj)); 
      },

      Joinus.prototype._gender = function(str) {
	    var num = 2;
	    if (str == 'man') {
		num = 2;
	    } else if (str == 'woman') {
		num = 1;
	    }
	    return num;
      };

      Joinus.prototype._renderError = function(obj) {
	     var dom =  $('#joinus_box').find('.'+obj.field+'');

	     if (obj.field =='gender' || obj.field == 'lookForGender') {
		 if (dom.next().hasClass('err')) {
		     dom.next().remove();
		 }
		 if (!obj.bool) {
		 dom.after("<div class='err'>"+obj.msg+"</div>");
		 }
	     } else {
		 if (dom.next().hasClass('err')) {
		     dom.next().remove();
		     dom.find('input').removeAttr('style').removeClass('input_err');
		 }
		 if (!obj.bool) {
		     dom.after("<div class='err'>"+obj.msg+"</div>");
		     dom.find('input').css('borderColor','#f00').addClass('input_err');
		 }
             }
      };

      Joinus.prototype._regModelValidata = function(model) {
         var tthis=this,bool = true;
         for (var x in model) {
             (function(x,model){
               var obj =  tthis._regFieldValidata(x,model);
                   tthis._renderError(obj);
                   if (!obj.bool) {                   
                       bool = false;
                   } 
             })(x,model);
         }
         return bool;
      };

      Joinus.prototype._regFieldValidata = function(field,model) {
            var obj = {bool : true, field:field};
            switch(field) {
               case 'email' :
                     if (model[field] == null || $.trim(model[field]) == '') { 
                         obj.bool = false;
                         obj.msg = lang.required;
                     } else if (!util.isEmail(model[field])) {
                         obj.bool = false;
                         obj.msg = lang.email_format_error;
                     }
               break;
 
               case 'userName': 
                     if (model[field] == null || $.trim(model[field]) == '') {
                         obj.bool = false;
                         obj.msg = lang.required;
                     } else if (!util.isLength(model[field],6,18)) {
                         obj.bool = false;
                         obj.msg = lang.username_format_error+'[6-18].';
                     }
               break;

               case 'passWord':
                     if (model[field] == null || $.trim(model[field]) == '') {
                         obj.bool = false;
                         obj.msg = lang.required;
                     } else if (!util.isLength(model[field],6,18)) {
                         obj.bool = false;
                         obj.msg = lang.password_format_error+'[6-18].';
                     }
               break;

               case 'lookForGender':
               case 'gender':
                    if (model[field] == null || model[field] == '') {
                        obj.bool = false;
                        obj.msg = lang.selected;
                    }
               break;     
               case 'age':
               case 'loction':
               case 'zipCode':
                    if (model[field] == null || model[field] == '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    }                   
               break;  
               case 'img':
               break;

               case 'lookForAge' :
                    if (model[field] == null || model[field] == '') {
                        obj.bool = false;
                        obj.msg = lang.required;
                    } else {
                        var arr = model[field].split('-');
                        if (arr[1]<arr[0]) {
                            obj.bool = false;
                            obj.msg = lang.joinus_lookfor_age;
                        }
                       
                    }
               break;
            }     
            return obj;
    };
   


});
